<template>
    <div id="particle-container">
        <vue-particles id="tsparticles" :options="particlesOption"></vue-particles>
        <div class="login-container">
            <el-row>
                <el-col :span="12" :xs="0"></el-col>
                <el-col :span="12" :xs="24">
                    <div class="loginBox">
                        <h3>企业资源管理系统</h3>
                        <el-form class="login-form" :rules="rules" :model="user" ref="ruleFormRef">
                            <el-form-item label="用户名" label-width="80px" prop="username">
                                <el-input v-model="user.username" placeholder="请输入用户名" clearable></el-input>
                            </el-form-item>
                            <el-form-item label="密码" label-width="80px" prop="password">
                                <el-input type="password" v-model="user.password" placeholder="请输入密码" clearable
                                    show-password></el-input>
                            </el-form-item>
                            <el-form-item label-width="80px">
                                <el-button type="primary" @click="login(ruleFormRef)" class="login-btn" :loading="isLogin">登录</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script setup>
// 导出tsparticles配置文件对象
import particlesOption from '@/assets/particlesOption.json'
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useHomeStore } from '@/stores/index'
import router from '@/router';
import {insertLoginLog}from '@/apis/zs/index'
const user = ref({ username: '', password: '' })
const ruleFormRef = ref();
const store = useHomeStore();
const isLogin = ref(false)
/**
 * 校验用户名是否符合规则
 * @param rule 规则对象
 * @param value  文本内容
 * @param callback 验证通过回调函数
 * 
 */
const validatorUserName = (rule, value, callback) => {
    if (value.length >= 6) {
        callback()
    } else {
        callback(new Error('用户名长度必须大于等于6位'))
    }
}

/**
 * 校验用户密码是否符合规则
 * @param rule  规则对象
 * @param value  文本内容
 * @param callback 校验通过回调函数
 */
const validatorPassWord = (rule, value, callback) => {
    const regex = /^[a-zA-Z0-9_]+$/
    if (value.length >= 6 && /^[a-zA-Z0-9_]+$/.test(value)) {
        callback()
    } else {
        callback(new Error('密码不符合要求'))
    }
}

// 自定义校验规则,key为自定义规则名称绑定prop，validator为自定义规则函数
const rules = {
    username: [
        { trigger: 'blur', validator: validatorUserName }
    ],
    password: [
        { trigger: 'blur', validator: validatorPassWord }
    ]

}
// 登录方法
const login = (formEl) => {
    isLogin.value = true
    if (!formEl) return
    formEl.validate(async (valid) => { // 验证表单
        if (valid) { // 表单验证通过
            let LoginLogObj = {
                userName: user.value.username,
                status: '0'
            }
            const browserInfo = getBrowserInfo(navigator.userAgent) // 获取浏览器信息
            // 添加登录信息
            LoginLogObj.os = browserInfo.os
            LoginLogObj.browser = browserInfo.browser
            let locationInfo = await fetch(`/api/ws/location/v1/ip?key=6LDBZ-BF4HK-G2ZJA-ABCNH-3A44S-7OFZI`)
            let locationData = await locationInfo.json()
            LoginLogObj.loginLocation = locationData.result.ad_info.province.concat(locationData.result.ad_info.city, locationData.result.ad_info.district).trim()
            LoginLogObj.ipAddr = locationData.result.ip
            const token = await store.requestLogin(user.value.username, user.value.password)
            if (!token) {
                LoginLogObj.status = '1'
                LoginLogObj.msg = '用户名或密码错误!'
                await insertLoginLog(LoginLogObj) // 记录登录日志
                return
            }
            localStorage.setItem('token', token) // 保存token到本地缓存
            store.isLogin = true // 设置登录状态
            LoginLogObj.msg = '登录成功'
            await insertLoginLog(LoginLogObj) // 记录登录日志
            isLogin.value = false
            router.push('/index') // 跳转到首页
            ElMessage.success('登录成功!'); // 显示登录成功消息
        } else {
            ElMessage.error('输入有误，请检查!'); // 表单验证失败，显示错误消息
        }
    });
}

/**
 * 获取浏览器信息
 * @param userAgent 浏览器userAgent
 */
function getBrowserInfo(userAgent) {
    // 此处顺序很重要，并且对于未列出的浏览器，这可能会报错。
    let browserInfo = {}
    if (userAgent.includes("Firefox")) {
        browserInfo.browser = "Mozilla Firefox"
    } else if (userAgent.includes("SamsungBrowser")) {
        browserInfo.browser = "Samsung Internet"
    } else if (userAgent.includes("Opera") || userAgent.includes("OPR")) {
        browserInfo.browser = "Opera"
    } else if (userAgent.includes("Edge")) {
        browserInfo.browser = "Microsoft Edge(Legacy)"
    } else if (userAgent.includes("Edg")) {
        browserInfo.browser = "Microsoft Edge(Chromium)"
    } else if (userAgent.includes("Chrome")) {
        browserInfo.browser = "Google Chrome 或 Chromium"
    } else if (userAgent.includes("Safari")) {
        browserInfo.browser = "Apple Safari"
    } else {
        browserInfo.browser = "未知浏览器"
    }
    if (userAgent.includes("Android")) {
        browserInfo.os = "Android"
    } else if (userAgent.includes("iPhone")) {
        browserInfo.os = "iPhone"
    } else if (userAgent.includes("iPad")) {
        browserInfo.os = "iPad"
    } else if (userAgent.includes("Macintosh")) {
        browserInfo.os = "Mac OS X"
    } else if (userAgent.includes("Windows")) {
        browserInfo.os = "Windows"
    } else {
        browserInfo.os = "未知系统"
    }
    return browserInfo
}

</script>

<style scoped>
#particle-container {
    position: absolute;
    width: 100%;
    height: 100vh;
    z-index: -999;
    background-image: url("@/assets/imgs/背景7.png");
    background-size: cover;
    background-position: 50% 50%;
    background-repeat: no-repeat;
    overflow: hidden;
}

.login-container .loginBox {
    position: relative;
    width: 50%;
    top: 30vh;
    border-radius: 5px;
    padding: 30px;
    color: aliceblue;
}

.login-container .loginBox h3 {
    text-align: center;
    margin-bottom: 20px;
}

.login-container .loginBox .login-btn {
    width: 100%;
    cursor: pointer;
}

.loginBox {
    width: 200px;
    height: 200px;
    background-color: rgba(0, 0, 0, 0.4);
}
</style>
